package org.gd.helloconcurrent.futures_and_callables;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicLong;

public class MyRunnableMain {

    private static final int NTHREDS = 10;

    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(NTHREDS);
        for (int i = 0; i < 500; i++) {
            Runnable worker = new MyRunnable(10000000L + i);
            executor.execute(worker);
        }
        // This will make the executor accept no new threads
        // and finish all existing threads in the queue
        executor.shutdown();
        // Wait until all threads are finish
        long t1 = System.currentTimeMillis();
        AtomicLong t2 = new AtomicLong(System.currentTimeMillis());
        while (!executor.isTerminated()) {
            t2.set(System.currentTimeMillis());
        }
        System.out.printf("Finished all threads. Time: %d\n", t2.addAndGet(-t1));
    }
}
